<template>
  <div class="lark-apply-trail-feature" v-if="showTip">
    <i
      class="iconfont icon-warning-circle-fill lark-apply-trail-feature-info-icon"
    ></i>
    <span> 立即体验VIP服务：VIP功能、专属解决方案 </span>

    <div class="lark-apply-trail-feature-button" @click="showApplyDialog">
      点击申请
    </div>

    <i
      class="iconfont icon-close lark-apply-trail-feature-close-icon"
      @click="close"
    ></i>

    <base-modal
      append-to-body
      v-show="showDialog"
      width="808px"
      class="lark-apply-trail-feature-dialog-modal"
      @close="closeDialog"
    >
      <div class="lark-apply-trail-feature-dialog-left">
        <img :src="logoImage" alt="" class="logo" />
        <div class="welcome">
          你好，{{ displayName }}
          <br />
          欢迎使用售后宝<span>（试用版）</span>
        </div>
        <div class="help-tip">
          如需要更好的体验系统，获取专属解决方案，
          <br />
          请留下您的联系方式
          <br />
          您的专属服务顾问将在第一时间联系您
        </div>
      </div>
      <div class="lark-apply-trail-feature-dialog-right">
        <div class="msg-form">
          <div class="title">申请VIP专属顾问</div>
          <div class="tip">
            专属服务顾问将第一时间与您联系<br />请您保持电话畅通
          </div>

          <form-builder
            ref="FormBuilderComponent"
            :fields="fields"
            :value="form"
            @update="updateForm"
          >
            <template slot="serialNumber" slot-scope="{ field }">
              <form-item
                :validation="phoneValidateRule"
                :label="field.displayName"
              >
                <form-phone
                  :field="field"
                  :value="form.phone"
                  @update="updateForm"
                />
              </form-item>
            </template>
            <template slot="code" slot-scope="{ field }">
              <form-item :label="field.displayName" validation>
                <div class="lark-apply-trail-feature-dialog-code-item">
                  <form-text
                    is-not-input-zh
                    is-only-number
                    :field="field"
                    :value="form.code"
                    @update="handlerOnUpdateCode"
                  />
                  <div
                    class="count-text lark-apply-trail-feature-dialog-code-text"
                    v-if="isCounting"
                  >
                    <van-count-down
                      ref="countDown"
                      time="60000"
                      auto-start
                      format="ss"
                      @finish="handlerFinishCounting"
                    />s后重新发送
                  </div>
                  <span
                    v-else
                    type="button"
                    class="lark-apply-trail-feature-dialog-code-text lark-apply-trail-feature-dialog-code-btn"
                    @click="handlerClickSendCode"
                  >
                    获取验证码
                  </span>
                </div>
              </form-item>
            </template>
          </form-builder>
          <div class="confirm-btn" @click="save" v-loading="loading">立即申请</div>
        </div>
      </div>
    </base-modal>
  </div>
</template>
<script>
/* api */
import { larkRetentionSave, sendVerifyCode } from '@src/api/CommonApi'
/* util */
import { findComponentDownward } from '@src/util/assist';
import { isString } from '@src/util/type';
import CountDown from 'vant/lib/count-down';
import platform from '@src/util/platform'

import { getRootWindowInitData } from '@src/util/window'

import { validatePhone as validatePhone_ } from '@src/util/validator'
import { getLocalesOssUrl } from '@src/util/assets'
const logoImage = getLocalesOssUrl('/logo_green.png')
const IS_NUMBER_REG = /^\d{1,}$/;
export default {
  name: 'lark-apply-trail-feature',
  props:{
    tenantName:{
      type: String,
      default:''
    }
  },
  data() {
    return {
      logoImage,
      showTip: true,
      showDialog: false,
      fields: [
        {
          defaultValue: null,
          displayName: '手机号',
          fieldName: 'phone',
          formType: 'phone',
          guideProfessions: [],
          id: 344989,
          isDelete: 0,
          isGuideData: false,
          isHidden: 0,
          isNull: 0,
          isSearch: 0,
          isSystem: 0,
          isVisible: true,
          orderId: 23,
          maxlength: 11,
          placeHolder: '请输入',
          setting: {
            defaultValueConfig: {
              isCurrentPhone: 0,
            },
          },
          tenantId: '',
        },
        {
          defaultValue: null,
          displayName: '验证码',
          fieldName: 'code',
          formType: 'text',
          guideProfessions: [],
          id: 344990,
          isDelete: 0,
          isHidden: 0,
          isNull: 0,
          isSearch: 0,
          isSystem: 0,
          isVisible: true,
          orderId: 32,
          maxlength: 6,
          placeHolder: '请输入',
          setting: {
            limitConig: {
              max: '',
              min: '',
              type: 1,
              isLimit: 0,
            },
          },
          limitConig: { max: '', min: '', type: 1, isLimit: 0 },
          tenantId: '',
        },
      ],
      form: {
        phone: '',
        code: '',
      },
      isCounting: false,
      loading:false,
      displayName:'',
    };
  },
  components: {
    [CountDown.name]: CountDown,
  },
  mounted( ){
    let rootWindowData = getRootWindowInitData()
    this.displayName = rootWindowData?.user?.displayName || ''
  },
  methods: {
    phoneValidateRule(value, field, changeStatus) {
      changeStatus(true);
      return new Promise((resolve, reject) => {
        changeStatus(false);
        if (value == null || !value.toString().length)
          return resolve(`请输入${field.displayName}`);
        if (!validatePhone_(value, 1))
          return resolve('请输入正确的电话或者手机号');
        resolve(null);
      });
    },
    close() {
      this.showTip = false;
      this.$emit('close')
    },
    init(){
      this.form = {
        phone:'',
        code:''
      }
      this.$nextTick(()=>{
        (this.$refs.FormBuilderComponent?.$children || []).forEach(el => {
          el?.resetValidationStatus()
        });
      })
    },
    showApplyDialog() {
      this.showDialog = true;
      this.init()
    },
    closeDialog() {
      this.showDialog = false;
    },

    updateForm({ field, newValue, oldValue }) {
      let { fieldName, displayName } = field;
      this.$set(this.form, fieldName, newValue);
    },
    handlerOnUpdateCode(data) {
      let { newValue } = data;

      if (!IS_NUMBER_REG.test(newValue)) {
        data.newValue = '';
      }

      this.updateForm(data);
    },
    handlerFinishCounting() {
      this.stopCounting();
    },
    startCounting() {
      this.isCounting = true;
    },
    stopCounting() {
      this.isCounting = false;
    },
    getPhoneItemComponent() {
      try {
        const FormPhoneComponent = findComponentDownward(
          this.$refs.FormBuilderComponent,
          'form-phone'
        );
        return FormPhoneComponent?.$parent;
      } catch (error) {
        Log.error(error);
        return null;
      }
    },

    validatePhone() {
      const phoneItemComponent = this.getPhoneItemComponent();
      if (!phoneItemComponent) return Promise.resolve(true);

      return phoneItemComponent.validate();
    },
    async handlerClickSendCode() {
      const isValidatedPhone = await this.validatePhone();
      if (isString(isValidatedPhone)) return;

      // 开始计时
      this.startCounting();
      // 发送验证码
      const { succ } = await sendVerifyCode({phone:this.form.phone,type:'FEISHU_LIUZHI_VERIFY_CODE'})
      if (!succ) {
        this.stopCounting()
        platform.alert(message);
      }
    },
    save() {
      this.$refs.FormBuilderComponent?.validate().then(async(valid)=>{
        if (!valid) return
        this.loading = true
        let {phone,code} = this.form
        let data = {
          phone,
          code,
          type:'FEISHU_LIUZHI_VERIFY_CODE',
          name:this.displayName
        }
        const { succ,message } = await larkRetentionSave(data)
        this.loading = false
        if (!succ) return platform.alert(message);
        
        platform.alert('申请成功')
        localStorage.setItem('lark_trail',false)
        this.showDialog = false
        this.showTip = false
      })
    }
  },
};
</script>
<style lang="scss">
@import './trail.scss';
.ss{
  background-repeat: no-repeat;
}
</style>
